<template>
  <div class="serial-port">测试串口</div>
  <el-button type="primary" @click="connectToSerialPort">连接串口</el-button>
  <el-input
    v-model="inputData"
    maxlength="50"
    placeholder="输入发送数据内容"
    show-word-limit
    type="textarea"
  />
  <el-button type="success" @click="sendData">发送数据</el-button>
  <el-button type="danger" @click="cutPort">断开串口</el-button>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";

// import { useRoute, useRouter } from "vue-router";

// const route = useRoute();
// const router = useRouter();

const port = ref("");
const ports = ref([]);
const reader = ref("");

const connectToSerialPort = async () => {
  try {
    // 提示用户选择一个串口
    port.value = await navigator.serial.requestPort();

    // 获取用户之前授予该网站访问权限的所有串口。
    ports.value = await navigator.serial.getPorts();

    // console.log(port.value, ports.value);
    console.log(port.value);
    // 等待串口打开
    await port.value.open({ baudRate: 9600 });

    // console.log(typeof port.value);
    ElMessage({
      message: "成功连接串口",
      type: "success",
    });
    // readData(port.value);
    readData();
  } catch (error) {
    // 处理连接串口出错的情况
    console.log("Error connecting to serial port:", error);
  }
};

const readData = async () => {
  reader.value = port.value.readable.getReader();
  console.log(reader);
  // 监听来自串口的数据
  while (true) {
    const { value, done } = await reader.value.read();
    if (done) {
      // 允许稍后关闭串口
      reader.value.releaseLock();
      break;
    }
    // 获取发送的数据
    const serialData = new TextDecoder().decode(value);
    console.log(serialData);
    // value 是一个 Uint8Array
    console.log(value);
  }
};

const inputData = ref("");
//
const sendData = async () => {
  // if (port.value && port.value.isOpen) {
  if (port.value) {
    if (inputData.value) {
      const writer = port.value.writable.getWriter();
      console.log("发送数据");
      await writer.write(new TextEncoder().encode(inputData.value));
      await writer.close();
    } else {
      return ElMessage({
        message: "输入需要发送的数据内容",
        type: "warning",
        showClose: true,
        grouping: true,
        duration: 2000,
      });
    }
  } else {
    ElMessage({
      message: "串口未连接或未打开！",
      type: "warning",
      showClose: true,
      grouping: true,
      duration: 2000,
    });
    // console.error("串口未连接或未打开！");
  }
};

// 断开接口
const cutPort = async () => {
  if (port.value !== "") {
    await reader.value.cancel();
    await port.value.close();
    port.value = "";
    console.log("断开串口连接");
    ElMessage({
      message: "已成功断开串口连接",
      type: "success",
    });
  } else {
    ElMessage({
      message: "请先连接或打开串口",
      type: "warning",
      showClose: true,
      grouping: true,
      duration: 2000,
    });
    // console.error("串口未连接或未打开！");
  }
};

onMounted(() => {
  // 判断浏览器支持串口通信
  if ("serial" in navigator) {
    console.log(true);
  } else {
    console.log(false);
  }
  // 页面刷新提示
  // window.onbeforeunload = e => {
  //   console.log(e);
  //   // 兼容IE8和Firefox 4之前的版本
  //   if (e) {
  //     e.returnValue = '关闭提示'
  //   }
  //   // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
  //   return '关闭提示'
  // }
});
</script>

<style></style>